﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ueEngine.Framework.Empires
{
    internal class TempleteHeadAnalyzer : BaseHeadAnalyzer
    {
        #region BuildHead
        public override string Analyzer(string identity, string fileStream, string templetePath)
        {
            string headStream = string.Empty;
            Regex reg = new Regex(PageBuilderRegexpLib.HeadPicker);
            if (!reg.IsMatch(fileStream))//匹配head字段
            {
                return fileStream;
            }
            headStream = reg.Match(fileStream).Groups[0].ToString(); //获得head段

            headStream = CorrectionTitleAndKeyWord(headStream, identity); //设置key和title
            headStream = CorrectionHeadSrc(headStream, templetePath); //矫正head中src链接，不允许跳出模板根目录
            headStream = CorrectionHeadhref(headStream, templetePath); //矫正head中链接，不允许跳出模板目录
            return headStream;
        }
        protected override string CorrectionTitleAndKeyWord(string headStream, string identity)
        {
            string orgTaK = LoadTitleAndKeyword(identity);
            if (!String.IsNullOrEmpty(orgTaK))
            {
                string title = String.Format("<title>{0}</title>", orgTaK.Split('$')[0]);
                string keyword = String.Format("<meta name=\"keywords\" content=\"{0}\" />", orgTaK.Split('$')[1]);
                Regex kreg = new Regex(PageBuilderRegexpLib.Keywordspicker, RegexOptions.IgnoreCase);
                if (kreg.IsMatch(headStream))
                {
                    headStream = kreg.Replace(headStream, keyword);
                }
                else
                {
                    headStream = keyword + "*r*n" + headStream;
                }
                Regex treg = new Regex(PageBuilderRegexpLib.TitlePicker, RegexOptions.IgnoreCase);
                if (treg.IsMatch(headStream))
                {
                    headStream = treg.Replace(headStream, title);
                }
                else
                {
                    headStream = title + "*r*n" + headStream;
                }

                return headStream;
            }
            return headStream;
        }
        protected override string LoadTitleAndKeyword(string identity)
        {
            return string.Empty;
        }
        protected override string CorrectionHeadSrc(string headStream,string templetePath)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.SrcPicker, RegexOptions.IgnoreCase);
            MatchCollection matchs = reg.Matches(headStream);
            int addindex = 0;
            foreach (Match item in matchs)
            {
                string path = item.ToString().Replace("/", "\\");
                if (String.IsNullOrEmpty(path))
                {
                    continue;
                }
                if (path.Contains(".."))
                {
                    List<string> piece = path.Split('\\').ToList();
                    int pevtimes = piece.Where(c => c == "..").Count();
                    System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                    for (int i = 0; i < pevtimes; i++)
                    {
                        dir = dir.Parent;
                    }
                    string currentPath = dir.FullName.EndsWith("\\") ? dir.FullName : dir.FullName + "\\";
                    if (!currentPath.Contains(AppDomain.CurrentDomain.SetupInformation.ApplicationBase))
                    {
                        headStream = reg.Replace(headStream, "javascript:;", 1, item.Index + addindex);
                        addindex += currentPath.Length - path.Length;
                    }
                    else
                    {
                        currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "");
                        currentPath += Concat(piece.Where(c => c != "..").ToList());
                        headStream = reg.Replace(headStream, currentPath.StartsWith("\\") ? currentPath : "\\" + currentPath, 1, item.Index + addindex);
                        addindex += currentPath.Length - path.Length;
                    }
                }
                else
                {
                    System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                    string currentPath = dir.FullName.EndsWith("\\") ? dir.FullName : dir.FullName + "\\";
                    currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "");
                    if (currentPath.EndsWith("\\"))
                    {
                        if (path.StartsWith("\\"))
                        {
                            currentPath += path.Substring(1);
                        }
                        else
                        {
                            currentPath += path;
                        }
                    }
                    else
                    {
                        if (path.StartsWith("\\"))
                        {
                            currentPath += path;
                        }
                        else
                        {
                            currentPath += "\\" + path;
                        }
                    }
                    headStream = reg.Replace(headStream, currentPath.StartsWith("\\") ? currentPath : "\\" + currentPath, 1, item.Index + addindex);
                    addindex += currentPath.Length - path.Length;
                }
            }
            return headStream;
        }       
        protected override string CorrectionHeadhref(string headStream, string templetePath)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.HrefPicker, RegexOptions.IgnoreCase);
            MatchCollection matchs = reg.Matches(headStream);
            int addindex = 0;
            foreach (Match item in matchs)
            {
                string path = item.ToString().Replace("/", "\\");
                if (String.IsNullOrEmpty(path))
                {
                    continue;
                }
                if (path.Contains(".."))
                {
                    List<string> piece = path.Split('\\').ToList();
                    int pevtimes = piece.Where(c => c == "..").Count();
                    System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                    for (int i = 0; i < pevtimes; i++)
                    {
                        dir = dir.Parent;
                    }
                    string currentPath = dir.FullName.EndsWith("\\") ? dir.FullName : dir.FullName + "\\";
                    if (!currentPath.Contains(AppDomain.CurrentDomain.SetupInformation.ApplicationBase))
                    {
                        headStream = reg.Replace(headStream, "javascript:;", 1, item.Index + addindex);
                        addindex += currentPath.Length - path.Length;
                    }
                    else
                    {
                        currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "");
                        currentPath += Concat(piece.Where(c => c != "..").ToList());
                        headStream = reg.Replace(headStream, currentPath.StartsWith("\\") ? currentPath : "\\" + currentPath, 1, item.Index + addindex);
                        addindex += currentPath.Length - path.Length;
                    }
                }
                else
                {
                    System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                    string currentPath = dir.FullName.EndsWith("\\") ? dir.FullName : dir.FullName + "\\";
                    currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "");
                    if (currentPath.EndsWith("\\"))
                    {
                        if (path.StartsWith("\\"))
                        {
                            currentPath += path.Substring(1);
                        }
                        else
                        {
                            currentPath += path;
                        }
                    }
                    else
                    {
                        if (path.StartsWith("\\"))
                        {
                            currentPath += path;
                        }
                        else
                        {
                            currentPath += "\\" + path;
                        }
                    }
                    headStream = reg.Replace(headStream, currentPath.StartsWith("\\") ? currentPath : "\\" + currentPath, 1, item.Index + addindex);
                    addindex += currentPath.Length - path.Length;
                }
            }
            return headStream;
        }
        #endregion

    }
}
